<template>
  <div class="box-border flex w-full h-full gap-[22px]">
    <div class="flex flex-col w-[calc(100%-532px)] h-full">
      <div class="flex flex-col h-[calc(100%-128px)] gap-4">
        <div
          class="h-[136px] w-full px-[60px] py-[20px] bg-white/50 rounded-[12px] border_white box-border"
        >
          <div class="text-[24px] font-semibold">{{ taskName }}</div>
          <div class="flex justify-between text-[18px] mt-6">
            <div>开机时间：{{ startTime || '- -' }}</div>
            <div>累计检测：{{ totalDetection }}</div>
            <div>有效告警：- -</div>
            <div>平均节拍：{{ averageBeat }}</div>
          </div>
        </div>
        <div
          class="h-[calc(100%-156px)] w-full bg-white/50 rounded-[12px] border_white box-border overflow-hidden relative"
        >
          <Video2 :url="rtspUrl"></Video2>
          <!-- <el-button class="absolute top-2 right-2" @click="handleRefreshVideo">
            <img src="../assets/images/refresh.png" class="w-4 h-4 mr-2" />刷新视频
          </el-button> -->
        </div>
      </div>
      <div class="h-[128px] w-full flex items-center justify-around">
        <el-button type="primary" plain class="!w-[315px] !h-[55px]" @click="handleEndTask"
          >结束任务</el-button
        >
        <el-button type="success" plain class="!w-[315px] !h-[55px]" @click="handlePauseTask">
          {{ isPaused ? '继续任务' : '暂停任务' }}
        </el-button>
      </div>
    </div>
    <div
      class="w-[510px] h-full box-border bg-white/40 rounded-[12px] border_white px-[100px] py-[2vw] relative"
    >
      <div class="text-[20px] font-semibold flex items-center justify-center">
        当前节拍：{{ currentBeat }}
        <span v-if="isAllDetected" class="ml-10 text-[#60C348] text-[36px] animate-ok">OK</span>
      </div>
      <div class="mt-[26px] flex flex-col gap-[20px] items-center">
        <div
          v-for="item in detection_objects"
          :key="item.id"
          class="flex items-center justify-center rounded-[8px] w-[315px] h-[55px]"
          :class="{
            'bg-[#60C348]': item.status === 1,
            'bg-error-ripple': item.status === 0,
          }"
        >
          <div class="text-[18px] text-white">{{ item.name }}</div>
        </div>
      </div>
      <div class="absolute bottom-4 left-1/2 -translate-x-1/2 flex flex-col gap-[24px]">
        <el-button type="primary" plain class="!w-[315px] !h-[55px]" @click="handleResetBeat"
          >重置节拍</el-button
        >
        <el-button type="success" plain class="!w-[315px] !h-[55px]" @click="handleForcePass"
          >强制放行</el-button
        >
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter, useRoute } from 'vue-router'
import { resetBeat, forcePass, getTaskRealTimeInfo, handleProcessControl } from '@/api/task'
import Video2 from '@/components/Video2.vue'
const router = useRouter()
const route = useRoute()
const taskName = ref('')
const taskId = ref('')
const pid = ref('')
const rtspUrl = ref('')
// 开机时间
const startTime = ref('')
watch(
  () => route.query,
  async (newVal) => {
    taskName.value = newVal.taskName
    const timeStr = taskName.value.replace('的任务', '')
    const year = timeStr.substring(0, 4)
    const month = timeStr.substring(4, 6)
    const day = timeStr.substring(6, 8)
    const hour = timeStr.substring(8, 10)
    const minute = timeStr.substring(10, 12)
    startTime.value = `${year}-${month}-${day} ${hour}:${minute}`
    pid.value = newVal.pid
    taskId.value = newVal.taskId
    // 转换 rtspUrl 格式
    const originalUrl = newVal.rtspUrl
    if (originalUrl) {
      const streamId = originalUrl.split('/').pop()
      // 本地
      rtspUrl.value = `http://192.168.140.170:8080/live/${streamId}.flv`
      // 生产环境
      // rtspUrl.value = `http://192.168.204.24:8080/live/${streamId}.flv`
    }
  },
  { immediate: true },
)
// 当前节拍
const currentBeat = ref(0)

// 累计检测
const totalDetection = ref(0)
// 有效告警
const validAlarm = ref(0)
// 平均节拍
const averageBeat = computed(() => {
  if (!startTime.value || !totalDetection.value) return '- -'
  const startTimeMs = new Date(startTime.value).getTime()
  const currentTimeMs = Date.now()
  const diffMinutes = (currentTimeMs - startTimeMs) / (1000 * 60)
  const average = (diffMinutes / totalDetection.value).toFixed(1)
  return `${average} min/件`
})

const detection_objects = ref([])

const isPaused = ref(false)

const handleEndTask = async () => {
  try {
    await handleProcessControl({ task_id: taskId.value, action: 'kill' })
    ElMessage.success('任务已结束')
    router.push('/')
  } catch (error) {
    ElMessage.error('结束任务失败')
  }
}

const handlePauseTask = async () => {
  try {
    isPaused.value = !isPaused.value
    if (isPaused.value) {
      await handleProcessControl({
        task_id: taskId.value,
        action: 'suspend',
      })
      if (timer) {
        clearInterval(timer)
        timer = null
      }
      ElMessage.success('任务已暂停')
    } else {
      await handleProcessControl({ task_id: taskId.value, action: 'resume' })
      getTaskRealTimeData()
      timer = setInterval(getTaskRealTimeData, 2000)
      ElMessage.success('任务已恢复')
    }
  } catch (error) {
    ElMessage.error('暂停或恢复任务失败')
  }
}

const handleResetBeat = async () => {
  try {
    await resetBeat({ task_id: taskId.value })
    // detection_objects.value = detection_objects.value.map((item) => {
    //   return { ...item, status: 0 }
    // })
    ElMessage.success('重置节拍成功')
  } catch (error) {
    ElMessage.error(error.message)
  }
}

const handleForcePass = async () => {
  try {
    await forcePass({ task_id: taskId.value })
    ElMessage.success('强制放行成功')
  } catch (error) {
    ElMessage.error(error.message)
  }
}

// const getTaskRealTimeData = async () => {
//   const res = await getTaskRealTimeInfo({ task_id: taskId.value })
//   totalDetection.value = res.data.beats_cnt

//   // 根据返回的current_states动态生成detection_objects
//   if (res.data.current_states) {
//     const newDetectionObjects = []
//     // 处理目标1-5
//     for (let i = 1; i <= 5; i++) {
//       if (String(i) in res.data.current_states) {
//         newDetectionObjects.push({
//           id: i,
//           name: `目标${i}`,
//           status: res.data.current_states[String(i)],
//         })
//       }
//     }
//     // 处理箱子
//     if ('box' in res.data.current_states) {
//       newDetectionObjects.push({
//         id: 'box',
//         name: '箱子',
//         status: res.data.current_states.box,
//       })
//     }
//     detection_objects.value = newDetectionObjects
//     currentBeat.value = res.data.beats_cnt + 1
//   }
// }

const getTaskRealTimeData = async () => {
  const res = await getTaskRealTimeInfo({ task_id: taskId.value })
  totalDetection.value = res.data.beats_cnt

  // 根据返回的current_states动态生成detection_objects
  if (res.data.current_states) {
    const newDetectionObjects = []
    // 定义字段映射关系
    // const fieldMapping = {
    //   parts_package: '配件包',
    //   manual: '说明书',
    //   magnetic_ring: '磁环',
    //   mutual_inductor: '互感器',
    //   wifi: 'WI-FI',
    //   network: '通信网线',
    //   plate: '后挂板',
    //   box: '箱子',
    // }

    const fieldMapping = {
      白色硬板纸盒: '白色硬板纸盒',
      短棕色硬板纸盒: '短棕色硬板纸盒',
      线路包装: '线路包装',
      蓝色纸质说明书: '蓝色纸质说明书',
      运输纸箱: '运输纸箱',
      长棕色硬板纸盒: '长棕色硬板纸盒',
    }

    // 处理所有检测对象
    Object.entries(fieldMapping).forEach(([key, name]) => {
      if (key in res.data.current_states) {
        newDetectionObjects.push({
          id: key,
          name: name,
          status: res.data.current_states[key],
        })
      }
    })

    detection_objects.value = newDetectionObjects
    currentBeat.value = res.data.beats_cnt + 1
  }
}

// 添加定时器
let timer = null
let player = null
const isVideoLoading = ref(true)

const videoKey = ref(0)

const handleVideoPlaying = () => {
  isVideoLoading.value = false
}

const handleVideoError = (error) => {
  console.error('视频加载失败:', error)
  ElMessage.error('视频加载失败')
  isVideoLoading.value = false
}

const handleRefreshVideo = () => {
  videoKey.value++ // 通过改变 key 值强制组件重新渲染
  ElMessage.success('视频已刷新')
}

onMounted(() => {
  // 添加 beforeunload 事件监听器
  window.addEventListener('beforeunload', () => {
    handleProcessControl({ task_id: taskId.value, action: 'kill' }).catch((error) => {
      console.error('结束任务失败:', error)
    })
  })

  // 立即执行一次
  getTaskRealTimeData()
  // 设置定时器，每2秒执行一次
  timer = setInterval(getTaskRealTimeData, 2000)
})

onBeforeUnmount(() => {
  // 清除定时器
  if (timer) {
    clearInterval(timer)
    timer = null
  }

  // 移除 beforeunload 事件监听器
  window.removeEventListener('beforeunload', () => {
    handleProcessControl({ task_id: taskId.value, action: 'kill' })
  })
})

// 添加计算属性来检查是否所有对象都被检测到
const isAllDetected = computed(() => {
  return detection_objects.value.every((item) => item.status === 1)
})
</script>

<style scoped>
:deep(.el-button > span) {
  font-size: 16px;
}

@keyframes errorRipple {
  0% {
    background-color: #ff0000;
    box-shadow: 0 0 0 0 rgba(255, 0, 0, 0.7);
  }
  50% {
    background-color: #ff4444;
    box-shadow: 0 0 4px 8px rgba(255, 0, 0, 0.3);
  }
  100% {
    background-color: #ff0000;
    box-shadow: 0 0 0 0 rgba(255, 0, 0, 0.7);
  }
}

.bg-error-ripple {
  animation: errorRipple 1s infinite;
}

@keyframes okAnimation {
  0% {
    transform: scale(0.5);
    opacity: 0;
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.animate-ok {
  animation: okAnimation 1s ease-out infinite;
}
</style>
